home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 625 < prev    next >
Internet Message Format  |  1996-08-06  |  2KB

  1. Path: mail2news.demon.co.uk!wbriscoe.demon.co.uk
  2. From: walter briscoe <walter@wbriscoe.demon.co.uk>
  3. Newsgroups: comp.std.c
  4. Subject: Re: Restrictions on qsort compare function?
  5. Date: Fri, 22 Mar 96 08:00:00 GMT
  6. Distribution: world
  7. Message-ID: <827481600snz@wbriscoe.demon.co.uk>
  8. References: <4iokop$h4p@lyra.csx.cam.ac.uk>
  9. Reply-To: walter@wbriscoe.demon.co.uk
  10. X-NNTP-Posting-Host: wbriscoe.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.30
  12. X-Mail2News-Path: wbriscoe.demon.co.uk
  13.  
  14. In article <4iokop$h4p@lyra.csx.cam.ac.uk>
  15.            jkb@mrc-lmb.cam.ac.uk "James Bonfield" writes:
  16.  
  17. > Are there any limitations on what the sort function passed over to qsort can
  18. > do or return? I know it's meant to return < 0, 0 or > 0 for the various
  19. > compare operations, but which you return is purely up to your own comparison
  20. > system.
  21.  
  22. [snip]
  23.  
  24. > static int sort_func(const void *pa, const void *pb)
  25. > {
  26. >     const int *a = (int *)pa;
  27. >     const int *b = (int *)pb;
  28. >     return *a > *b;
  29. >
  30. > }
  31.  
  32. You need a function which returns "an integer less than, equal to, or
  33. greater than zero if the first argument is considered to be respectively
  34. less than, equal to, or greater than the second" [ ANSI/ISO 9899-1990
  35. 7.10.5.2].
  36.  
  37. sort_funct returns 0, 0, and 1, respectively for the 3 cases enumerated.
  38.  
  39. Brevity is satisfied by:
  40.      return *a < *b ? -1 : *a > *b;
  41.  
  42. You may find that conformity to the interface is better shown by:
  43.      return (*a < *b) ? -1 : ((*a == *b) ? 0 : 1);
  44.  
  45. I think I prefer to avoid the multiple dereferencing with:
  46.  
  47. static int sort_func(const void *pa, const void *pb)
  48. {
  49.     int a = *(const int *)pa;
  50.     int b = *(const int *)pb;
  51.  
  52.     return a < b ? -1 : a > b;
  53. }
  54. --
  55. walter briscoe
  56.